<?php
/**
 * Author: Traveler
 * Time  : 2021/12/25 0025 15:26
 */

namespace app\service;

use app\ErrorCode;
use app\model\StaffModel;
use sunshine\basic\BaseService;
use sunshine\exceptions\ApiException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class LoginService extends BaseService
{
    /**
     * 账号登录
     *
     * @param array $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function account(array $data): array
    {
        $staff = (new StaffModel)->where('cellphone', $data['username'])->find();

        // 用户名或密码不正确
        if (!$staff || $data['password'] !== $staff['password']) {
            throw new ApiException(ErrorCode::INCORRECT_LOGIN);
        }

        // 用户被禁用
        if ($staff['status'] === 0) {
            throw new ApiException(ErrorCode::USER_DISABLED);
        }

        // 保存登陆信息
        $staff['login_count'] += 1;
        $staff['login_ip']    = app()->request->ip();
        $staff['login_time']  = time();
        $staff->save();

        $payload = ['uid' => $staff['id']];

        return ['token' => generate_token($payload)];
    }
}